#include "devicesearch.h"
#include "ui_devicesearch.h"

#define UDP_SERVER "192.168.0.48"
#define UDP_PORT 9090
#define TCP_PORT 8888
DeviceSearch::DeviceSearch(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::DeviceSearch)
{
    ui->setupUi(this);
    tcpSocket = new QTcpSocket(this);
    connect(ui->pushButton, &QPushButton::clicked, this, &DeviceSearch::onSearchDevicesClicked);
    connect(ui->listWidget, SIGNAL(itemClicked(QListWidgetItem*)), this, SLOT(onListWidgetItemClicked(QListWidgetItem*)));

}

DeviceSearch::~DeviceSearch()
{
    delete ui;
}

void DeviceSearch::onSearchDevicesClicked()
{
    QJsonObject json;
    json["DISCOVER_SERVER"] = 1;
    QJsonDocument doc(json);


   QUdpSocket * udpSocket = new QUdpSocket(this);
   udpSocket->bind(8888,QUdpSocket::ShareAddress);
   connect(udpSocket, &QUdpSocket::readyRead, this, &DeviceSearch::onUdpSocketReadyRead);

   QByteArray datagram = doc.toJson();
   udpSocket->writeDatagram(datagram.data(),datagram.size(),QHostAddress(UDP_SERVER),UDP_PORT);

}

void DeviceSearch::onUdpSocketReadyRead()
{
    QString senderIP ;
    QHostAddress senderAddress;
    quint16 senderPort;
    QByteArray datagram;
    QUdpSocket *udpSocket = qobject_cast<QUdpSocket *>(sender());
    while (udpSocket->hasPendingDatagrams()) {
        datagram.resize(udpSocket->pendingDatagramSize());
        udpSocket->readDatagram(datagram.data(), datagram.size(), &senderAddress, &senderPort);
     qDebug()<<"设备发送数据:\n"<<datagram;
     // 解析JSON数据
     QJsonDocument doc = QJsonDocument::fromJson(datagram);
     QJsonObject json = doc.object();
     // 检查"type"键的值是否为2

     if (json.contains("DISCOVER_SERVER") && json["DISCOVER_SERVER"].toInt() == 2 &&
         json.contains("result") && json["result"].toInt() == 0) {

         // 获取发送者的IP地址并显示在listWidget中
         senderIP = senderAddress.toString();
         ui->listWidget->addItem(senderIP);

     }
    }
}

void DeviceSearch::onListWidgetItemClicked(QListWidgetItem *item)
{
    QString ip = item->text(); // 获取IP地址

    tcpSocket->connectToHost(ip, TCP_PORT); // 尝试连接到指定的端口，您需要替换port为实际的端口号

    // 连接成功的信号处理
    connect(tcpSocket, &QTcpSocket::connected, this, &DeviceSearch::onTcpConnected);
}
// TCP连接成功的槽函数
void DeviceSearch::onTcpConnected()
{
    qDebug() << "TCP连接成功!";
    connect(tcpSocket, &QTcpSocket::readyRead, this, &DeviceSearch::onTcpSocketReadyRead);
}

void DeviceSearch::onTcpSocketReadyRead()
{
     QByteArray data = tcpSocket->readAll();
     qDebug() << "收到的数据:" << data;
     // 这里可以解析数据，比如转换为JSON对象
     QJsonDocument doc = QJsonDocument::fromJson(data);
     QJsonObject json = doc.object();
}
